package cn.com.hatech.cdkey.module.index.controller;

import cn.com.hatech.cdkey.common.constant.LogActions;
import cn.com.hatech.cdkey.common.constant.WebConst;
import cn.com.hatech.cdkey.common.controller.BaseController;
import cn.com.hatech.cdkey.common.exception.TipException;
import cn.com.hatech.cdkey.common.result.RestResponse;
import cn.com.hatech.cdkey.common.utils.TaleUtils;
import cn.com.hatech.cdkey.common.utils.UserRequest;
import cn.com.hatech.cdkey.module.index.entity.User;
import cn.com.hatech.cdkey.module.index.service.ILogService;
import cn.com.hatech.cdkey.module.index.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.module.admin.controller
 * @className: IndexController
 * @author: xuruikai
 * @description: 后台管理首页控制器
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@Controller("adminIndexController")
@Transactional(rollbackFor = TipException.class)
@Slf4j
public class IndexController extends BaseController {

    @Resource
    private ILogService logService;

    @Resource
    private IUserService userService;

    /**
     * 页面跳转
     *
     * @return
     */
    @GetMapping(value = {"", "/index"})
    public String index(HttpServletRequest request) {
        return "cdkey/index";
    }

    /**
     * 个人设置页面
     */
    @GetMapping(value = "profile")
    public String profile() {
        return "dashboard/profile";
    }

    /**
     * admin 退出登录
     *
     * @return
     */
    @GetMapping(value = "logout")
    public String logout() {
        System.out.println("index-----------logout");
        return "login";
    }


    /**
     * 保存个人信息
     */
    @PostMapping(value = "/profile")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponse saveProfile(@RequestParam String screenName, @RequestParam String email, HttpServletRequest request, HttpSession session) {

        User users = UserRequest.getCurrentUser();
        if (StringUtils.isNotEmpty(screenName) && StringUtils.isNotEmpty(email)) {
            User temp = new User();
            temp.setId(users.getId());
            temp.setScreenName(screenName);
            temp.setEmail(email);
            userService.updateByUid(temp);
            logService.insertLog(LogActions.UP_INFO.getAction(), JSONObject.toJSONString(temp), UserRequest.getRemoteAddr(), UserRequest.getCurrentUserId());

            //更新session中的数据
            User original = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
            original.setScreenName(screenName);
            original.setEmail(email);
            session.setAttribute(WebConst.LOGIN_SESSION_KEY, original);
        }
        return RestResponse.ok();
    }

    /**
     * 修改密码
     */
    @PostMapping(value = "/password")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponse upPwd(@RequestParam String oldPassword, @RequestParam String password, HttpServletRequest request, HttpSession session) {
        User users = UserRequest.getCurrentUser();
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(password)) {
            return RestResponse.fail("请确认信息输入完整");
        }

        if (!users.getPassword().equals(TaleUtils.MD5Encode(users.getUsername() + oldPassword))) {
            return RestResponse.fail("旧密码错误");
        }
        if (password.length() < 6 || password.length() > 14) {
            return RestResponse.fail("请输入6-14位密码");
        }

        try {
            User temp = new User();
            temp.setId(users.getId());
            String pwd = TaleUtils.MD5Encode(users.getUsername() + password);
            temp.setPassword(pwd);
            userService.updateByUid(temp);
            logService.insertLog(LogActions.UP_PWD.getAction(), null, request.getRemoteAddr(), UserRequest.getCurrentUserId());

            //更新session中的数据
            User original = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
            original.setPassword(pwd);
            session.setAttribute(WebConst.LOGIN_SESSION_KEY, original);
            return RestResponse.ok();
        } catch (Exception e) {
            String msg = "密码修改失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                log.error(msg, e);
            }
            return RestResponse.fail(msg);
        }
    }
}
